#!/bin/python3

import os
import sys
import shutil

tb_bodys = """
`timescale 1ns/1ps

parameter memname   = "%s";
parameter bits      = %0d;
parameter words     = %0d;
parameter addrbits  = %0d;


module tb;

    %s mem_dut();

    initial begin
        integer fid;
        #1ns;
        $display("Test Passed: %%s", memname);
        fid = $fopen("result.log","w");
        $fwrite(fid, $sformatf("TestCase Passed: %%s\\n", memname) );
        $finish(2);
    end

endmodule

"""

mkfile_bodys = """

all: comp sim

comp:
\tvcs -full64 -sverilog -f ${ProjRTL}/rtl.f tb.sv

sim:
\t./simv

"""

def TestBenchGenerator(memname, bits, words, addrbits):
    if (os.path.exists(memname+"_sim_dir")) :
        shutil.rmtree(memname+"_sim_dir")
    os.makedirs(memname+"_sim_dir")
    fd = open(memname+"_sim_dir/tb.sv", "w")
    fd.write(tb_bodys%(memname, bits, words, addrbits, memname))
    fd.close()
    fd = open(memname+"_sim_dir/makefile", "w")
    fd.write(mkfile_bodys)
    fd.close()
    print("Memory TestBench Generator successful: %s_sim_dir"%(memname))


def TestMemorySim(memname, bits, words, addrbits):
    TestBenchGenerator(memname, bits, words, addrbits)
    if (os.system("cd %s_sim_dir; make"%(memname))):
        sys.exit("Sim Error: "+memname)
    print("Memory Test Sim successful: %s_sim_dir"%(memname))
    os.system("cat %s_sim_dir/result.log >> result_all.log"%(memname))


if __name__ == "__main__":
    if (os.path.exists("result_all.log")) :
        os.remove("result_all.log")
    os.environ["ProjRTL"] = os.path.abspath("../memorytest")
    TestMemorySim("TSMC_N3E_1024x4096_2PRFSRAM", 1024, 4096, 12)
    TestMemorySim("TSMC_N3E_2047x4096_2PRFSRAM", 2047, 4096, 12)
    TestMemorySim("TSMC_N3E_1280x4096_2PRFSRAM", 1280, 4096, 12)
    TestMemorySim("TSMC_N3E_2574x4096_2PRFSRAM", 2574, 4096, 12)




